package com.example.demo_music;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;


public class MainActivity<MyAdapter> extends AppCompatActivity implements View.OnClickListener, MyReceiver.DaiLi1, MyReceiver.DaiLi2 {
    MediaPlayer mp;
    private ListView listView;
    private List<Music> musicList;
    private MyAdapter myAdapter;
    private int curPos;
    private ImageView iv_play_pause;
    private ImageView iv_previous;
    private ImageView iv_next;
    private View v;
    private TextView song_title;
    private TextView song_artist;
    private Intent service;
    private boolean isPlaying = false;
    private MyReceiver receiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        receiver = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter("song");
        registerReceiver(receiver,intentFilter);
        receiver.sendSong((MyReceiver.DaiLi1) this);
        receiver.sendSong((MyReceiver.DaiLi2) this);
        mp = new MediaPlayer();
//        service = new Intent(this, MyService.class);
        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
               next();
            }
        });
        musicList = new ArrayList<>();
        musicList = getMusic();
        listView.setAdapter(new BaseAdapter() {
            @Override
            public int getCount() {
                return musicList.size();
            }

            @Override
            public Object getItem(int position) {
                return musicList.get(position);
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                convertView = LayoutInflater.from(MainActivity.this).inflate(R.layout.item_music, parent, false);
                TextView tv_title = convertView.findViewById(R.id.tv_title);
                TextView tv_artist = convertView.findViewById(R.id.tv_name);
                TextView tv_time = convertView.findViewById(R.id.tv_time);
                Music music = musicList.get(position);
                tv_title.setText(music.getTitle());
                tv_artist.setText(music.getArtist());
                tv_time.setText(getTime(music.getDuration()));
                return convertView;
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                service.putExtra("action", "play");
//                service.putExtra("pos", position);
////                startService(service);
//                isPlaying = true;
//                iv_play_pause.setSelected(isPlaying);
                play(position);
            }
        });
    }

    public void initView() {
        iv_play_pause = findViewById(R.id.iv_play_pause);
        iv_previous = findViewById(R.id.iv_previous);
        iv_next = findViewById(R.id.iv_next);
        listView = findViewById(R.id.list_music);
        song_title = findViewById(R.id.song_title);
        song_artist = findViewById(R.id.song_singer);
        iv_play_pause.setOnClickListener(this::play_pause);
        iv_next.setOnClickListener(this::toNext);
        iv_previous.setOnClickListener(this::toPrevious);
    }

    public void toNext(View v) {
        next();
//        service.putExtra("action", "next");
//        startService(service);
    }

    public void toPrevious(View v) {
        previous();
//        service.putExtra("action", "previous");
//        startService(service);
    }

    public void onClick(View v) {

    }

    public void play_pause(View view) {
        if(mp.isPlaying()){
            mp.pause();
        }else{
            mp.start();
        }
//        if (isPlaying) {
//            service.putExtra("action", "pause");
//            startService(service);
//        } else {
//            service.putExtra("action", "start");
//            startService(service);
//        }
//        isPlaying = !isPlaying;
//        iv_play_pause.setSelected(mp.isPlaying());
    }

        private void play(int position){
        try{
            mp.reset();
            mp.setDataSource(musicList.get(position).getData());
            mp.prepare();
            mp.start();
            curPos = position;
            iv_play_pause.setSelected(mp.isPlaying());
            Intent intent = new Intent("song");
            intent.putExtra("songartist",musicList.get(curPos).getTitle());
            intent.putExtra("songtitle", musicList.get(curPos).getArtist());
            intent.setPackage("com.example.demo_music");
            sendBroadcast(intent);
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    public void next(){
        ++curPos;
        if(curPos == musicList.size())
            curPos = 0;
        play(curPos);
    }
    public void previous(){
        --curPos;
        if(curPos == -1)
            curPos = musicList.size() - 1;
        play(curPos);
    }
    public List<Music> getMusic() {
        List<Music> musics = new ArrayList<>();
        String[] project = {
                MediaStore.Audio.Media.TITLE,
                MediaStore.Audio.Media.ARTIST,
                MediaStore.Audio.Media.DURATION,
                MediaStore.Audio.Media.DATA
        };
        Cursor cursor = getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                project,
                null,
                null,
                MediaStore.Audio.Media.TITLE
        );
        while (cursor.moveToNext()) {
            String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
            String artist = cursor.getString(1);
            long duration = cursor.getLong(2);
            String data = cursor.getString(3);
//            System.out.println(title + "," + artist + "," + duration + "," + data);
            musics.add(new Music(title, artist, duration, data));
        }
        return musics;
    }

    public void mediaScan(final Context context, File file) {
        System.out.println(file.getAbsolutePath());
        ArrayList<String> filelist = new ArrayList<>();
        File[] files = file.listFiles();
        for (File ff : files) {
            if (ff.getName().endsWith("mp3")) {
                filelist.add(ff.getAbsolutePath());
            }
        }
        int size = filelist.size();
        String[] array = (String[]) filelist.toArray(new String[size]);
        MediaScannerConnection.scanFile(context, array, null, new MediaScannerConnection.OnScanCompletedListener() {
            @Override
            public void onScanCompleted(String path, Uri uri) {
                Intent scanintent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                scanintent.setData(uri);
                context.sendBroadcast(scanintent);
            }
        });
    }

    public String getTime(long duration) {
        String time = "";
        long min = duration / 60000;
        long second = duration % 60000 / 1000;
        time = min + ":" + second;
        return time;
    }
    protected void onDestroy(){
        super.onDestroy();
        unregisterReceiver(receiver);
    }
    public void artistSet(String artist){
        song_artist.setText(artist);
    }
    public void titleSet(String title){
        song_title.setText(title);
    }

}
